<?php
/**
 * @Author: kaihui.wang
 * @Contact  hpuwang@gmail.com
 * @Version: 1.0.0
 * @Date: 2020/10/21 14:14
 */

namespace Eduxplus\WebsiteBundle\Service;


use Eduxplus\CoreBundle\Lib\Base\AppBaseService;
use Eduxplus\CoreBundle\Lib\Service\HelperService;
use Knp\Component\Pager\PaginatorInterface;
use Eduxplus\CmsBundle\Entity\CmsTutorialFav;

class TutorialService extends AppBaseService
{
    protected $helperService;
    protected $paginator;

    public function __construct(HelperService $helperService, PaginatorInterface $paginator)
    {
        $this->helperService = $helperService;
        $this->paginator = $paginator;
    }


    public function getNewestTutorials($limit=6){
        $sql = "SELECT a FROM Cms:CmsTutorial a WHERE a.status=1 ORDER BY a.createdAt DESC";
        $result = $this->db()->fetchAll($sql, [],0,$limit);
        return $result;
    }

    public function viewNumIncre($id)
    {
        $sql = "UPDATE Cms:CmsTutorial a SET a.viewNumber = a.viewNumber+1 WHERE a.id = :id ";
        $this->db()->execute($sql, ["id" => $id]);
    }

    public function getAllFirstCategory()
    {
        $sql = "SELECT a FROM Cms:CmsTutorialCategory a WHERE a.isShow =1 AND a.parentId = 0 ORDER BY a.sort DESC";
        $category = $this->db()->fetchAll($sql);
        return $category;
    }

    public function getTutorialList($category, $page, $pageSize)
    {

        $em = $this->getDoctrine()->getManager();
        $em = $this->db()->enableSoftDeleteable($em);
        
        $parameters = [];
        if ($category) {
            $dql = "SELECT a FROM Cms:CmsTutorial a WHERE a.status=1 AND a.firstCategoryId = :firstCategoryId ";
            $parameters["firstCategoryId"]= $category;
        } else {
            $dql = "SELECT a FROM Cms:CmsTutorial a WHERE a.status=1 ";
        }
        
        $dql = $dql." ORDER BY a.sort DESC, a.createdAt DESC ";

        $query = $em->createQuery($dql);
        if ($parameters) $query = $query->setParameters($parameters);
        $pagination = $this->paginator->paginate(
            $query,
            $page,
            $pageSize
        );

        $items = $pagination->getItems();
        $itemsArr = [];
        if ($items) {
            foreach ($items as $v) {
                $vArr =  $this->toArray($v);
                $vArr['updatedAtTime'] = strtotime($vArr["updatedAt"]);
                $itemsArr[] = $vArr;
            }
        }

        return [$pagination, $itemsArr];
    }

    public function getById($id, $chapterId)
    {
        $dql = "SELECT a FROM Cms:CmsTutorial a WHERE a.id =:id ";
        $detail = $this->db()->fetchOne($dql, ["id" => $id]);
        if (!$detail) return $detail;
        $detail['createdAtTime'] = $detail["createdAt"]->getTimestamp();

        $dql = "SELECT a FROM Cms:CmsTutorialCategory a WHERE a.id=:id";
        $category = $this->db()->fetchOne($dql, ["id" => $detail['firstCategoryId']]);
        $chapter = $this->getChapterTree(0,$id);
        $detail['chapter'] = $chapter;
        
        $chapterId = $chapterId?$chapterId:($chapter?$chapter[0]["id"]:0);
        if($chapterId){
            $detail['content'] = $this->getContent($chapterId);
        }else{
            $detail['content']=[];
        }

        $detail['category'] = $category;
        $detail['chapterId'] =  $chapterId;
        return $detail;
    }

    public function getContent($id){
        $dql = "SELECT a FROM Cms:CmsTutorialChapter a WHERE a.id =:id ";
        $detail = $this->db()->fetchOne($dql, ["id" => $id]);
        return $detail;
    }

    public function getChapterTree($parentId, $tutorialId)
    {
        $sql = "SELECT a.id,a.name,a.parentId,a.tutorialId FROM Cms:CmsTutorialChapter a WHERE a.parentId = :parentId AND a.tutorialId = :tutorialId ORDER BY a.sort ASC";
        $items = $this->db()->fetchAll($sql, ['parentId' => $parentId, "tutorialId" => $tutorialId]);
        if (!$items) return [];
        $result = [];
        foreach ($items as &$v) {
            $tmp = $v;
            $child =  $this->getChapterTree($v['id'], $tutorialId);
            $tmp['childs'] = $child;
            $result[] = $tmp;
        }
        return $result;
    }

    
    public function getCategoryById($id)
    {
        $sql = "SELECT a FROM Cms:CmsTutorialCategory a WHERE a.id =:id";
        $category = $this->db()->fetchOne($sql,["id" => $id]);
        return $category;
    }

    public function favList($uid, $page, $pageSize){
        $dql = "SELECT a FROM Cms:CmsTutorialFav a WHERE a.uid =:uid";
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery($dql);
        $query= $query->setParameters(["uid"=>$uid]);
        $pagination = $this->paginator->paginate(
            $query,
            $page,
            $pageSize
        );
        
        $items = $pagination->getItems();
        $itemsArr = [];
        $tutorialIds = [];
        if ($items) {
            foreach ($items as $v) {
                $vArr =  $this->toArray($v);
                $tutorialIds[] = $vArr['tutorialId'];
            }
        }

        if ($tutorialIds) {
            $sql = "SELECT a FROM Cms:CmsTutorial a WHERE a.id IN (:id)";
            $itemsArr = $this->db()->fetchAllHard($sql, ["id" => $tutorialIds]);
            foreach ($itemsArr as &$v) {
                $v['updatedAtTime'] = $v["updatedAt"]->getTimestamp();
                $isDelete = is_null($v["deletedAt"])?0:1;
                if(!$isDelete){
                    $isDelete = $v["status"]?0:1;
                }
                $v['isDelete'] = $isDelete;
            }
        }
        return [$pagination, $itemsArr];
    }

    /**
     * 获取收藏
     * @param $goodsId
     * @param $uid
     */
    public function getFav($id, $uid){
        $sql = "SELECT a FROM Cms:CmsTutorialFav a WHERE a.uid=:uid AND a.tutorialId =:tutorialId ";
        return $this->db()->fetchOne($sql, ["uid"=>$uid, "tutorialId"=>$id]);
    }


    /**
     * 删除收藏
     *
     * @param $goodsId
     * @param $uid
     * @return bool
     */
    public function delFav($id, $uid){
        $sql = "SELECT a FROM Cms:CmsTutorialFav a WHERE a.uid=:uid AND a.tutorialId =:tutorialId ";
        $model =  $this->db()->fetchOne($sql, ["uid"=>$uid, "tutorialId"=>$id], 1);
        return $this->db()->hardDelete($model);
    }

    /**
     * 收藏商品
     * @param $goodsId
     * @param $uid
     */
    public function addFav($id, $uid){
        $model = new CmsTutorialFav();
        $model->setTutorialId($id);
        $model->setUid($uid);
        return $this->db()->save($model);
    }

    public function favNumIncre($id)
    {
        $sql = "UPDATE Cms:CmsTutorial a SET a.favNumber = a.favNumber+1 WHERE a.id = :id ";
        $this->db()->execute($sql, ["id" => $id]);
    }


    public function favNumDecre($id)
    {
        $sql = "UPDATE Cms:CmsTutorial a SET a.favNumber = a.favNumber-1 WHERE a.id = :id AND a.favNumber>0";
        $this->db()->execute($sql, ["id" => $id]);
    }

    public function clearFailure($uid){
        $sql = "SELECT a FROM Cms:CmsTutorialFav a LEFT JOIN Cms:CmsTutorial b WITH a.tutorialId =b.id WHERE a.uid =:uid AND ( b.status =0 OR b.deletedAt is not null )";
        $itemsArr = $this->db()->fetchAllHard($sql, ["uid" => $uid], 1);
        $this->db()->delete($itemsArr);
    }

}
